<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="keyword" placeholder="请输入操作人姓名"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="keyQuery">查询</el-button>
				</el-form-item>
			</el-form>
		</el-col>
		<!--列表-->
		<el-table :data="systemLogs" highlight-current-row v-loading="listLoading"
              :row-key="getRowKey" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55" :reserve-selection="true">
			</el-table-column>
			<el-table-column type="index" label="序号" width="60">
			</el-table-column>
			<el-table-column prop="operator" label="操作用户名" width="150"align="center">
			</el-table-column>
			<el-table-column prop="ip" label="ip" width="150" align="center" :show-overflow-tooltip="true">
			</el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="200" align="center" :show-overflow-tooltip="true">
      </el-table-column>
      <el-table-column prop="desc" label="操作描述" width="450" align="center" :show-overflow-tooltip="true">
      </el-table-column>
			<el-table-column label="操作" width="150" align="center">
				<template scope="scope">
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<el-pagination
          layout="total, sizes, prev, pager, next, jumper"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
          :page-size="pageSize"
          :current-page="currentPage"
          :total="totals"
          :page-sizes="[5, 8, 10]"
          style="float:right;">
			</el-pagination>
		</el-col>

		<!--添加修改对话框-->
		<el-dialog :title="title" :visible.sync="saveFormVisible" :close-on-click-modal="false">
			<el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
				<el-form-item label="店铺名称" prop="name">
					<el-input v-model="saveForm.name" auto-complete="off"></el-input>
				</el-form-item>
        <el-form-item label="店铺座机" prop="tel">
          <el-input v-model="saveForm.tel" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="店铺状态">
          <el-radio-group v-model="saveForm.state">
            <el-radio class="radio" :label="1">待审核</el-radio>
            <el-radio class="radio" :label="2">审核通过待激活</el-radio>
            <el-radio class="radio" :label="3">激活成功</el-radio>
            <el-radio class="radio" :label="4">驳回</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="店铺地址" prop="password">
          <el-input v-model="saveForm.address" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="店铺logo">
            <el-upload class="upload-demo"
                       action="http://localhost:8080/minio"
                       name="file"
                       :on-remove="handleRemove"
                       :on-success="handleSuccess"
                       :on-exceed="exceed"
                       :file-list="fileList"
                       :limit=1
                       accept=".jpg,.jpeg,.png,.gif"
                       list-type="picture">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传指定类型的图片</div>
            </el-upload>
        </el-form-item>
				<el-form-item label="管理员">
            <el-select v-model="saveForm.adminId" placeholder="请选择">
              <el-option
                  v-for="item in admins"
                  :label="item.username"
                  :value="item.id">
                <span style="float: left">{{ item.username }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{ item.phone }}</span>
              </el-option>
            </el-select>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="saveFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
			</div>
		</el-dialog>
	</section>
</template>

<script>
	import util from '../../common/js/util'
	//import NProgress from 'nprogress'
	import { getsystemLogListPage, removesystemLog, batchRemovesystemLog, editsystemLog, addsystemLog } from '../../api/api';

	export default {
    watch: {
      saveFormVisible(val) { // 当弹窗打开时
        // 重置表单，清空校验信息
        this.$nextTick(() => {
          //  延时到下一帧才开始，也就是页面刚刚渲染结束！！
          this.$refs.saveForm.clearValidate()
        })
      }
    },
    data() {
      return {
        // 分页相关数据
        currentPage: 1,
        pageSize: 5,
        totals: 0,
        systemLogs: [],
        listLoading: false,
        // 高级查询
        keyword: '',
        // 分页批量选中
        getRowKey(row){
          return row.id;
        },
        // 所有管理员
        admins: '',
        // 部门树
        deptTree: [],
        // 上传图片
        fileList: [],
        // 批量删除
        sels: [],//列表选中列
        //对话框数据
        title: '',
        saveForm: {
          id: null,
          name: '',
          tel: '',
          registerTime: '',
          address: '',
          logo: '',
          state: 1,
          adminId: null
        },
        saveFormVisible: false,//新增界面是否显示
        saveLoading: false, // 加载框
        saveFormRules: { // 表单项校验
          name: [
            {required: true, message: '请输入店铺名称', trigger: 'blur'}
          ],
          tel: [
            {required: true, message: '请输入店铺座机', trigger: 'blur'}
          ],
        },
      }
    },
    methods: {
      //分页查询
      getsystemLogs() {
        let param = {
          pageSize: this.pageSize,
          currentPage: this.currentPage,
          keyword: this.keyword
        };
        this.listLoading = true;
        this.$http.post("/systemLog", param).then(res => {
          this.systemLogs = res.data.data
          this.totals = res.data.totals
          this.listLoading = false;
        })
      },
      // 高级查询
      keyQuery() {
        this.currentPage = 1
        this.getsystemLogs();
      },
      //选择第几页时触发
      handleCurrentChange(currentPage) {
        this.currentPage = currentPage;
        this.getsystemLogs();
      },
      //选择每页显示记录条数
      handleSizeChange(pageSize) {
        this.pageSize = pageSize;
        this.getsystemLogs();
      },
      //删除
      handleDel: function (index, row) {
        this.$confirm('确认删除该记录吗?', '提示', {
          type: 'warning'
        }).then(() => {
          this.listLoading = true;
          this.$http.delete("/systemLog/" + row.id).then(res => {
            if (res.data.success) {
              let pageTotal = Math.ceil(this.totals / this.pageSize)
              if (this.currentPage != 1 && this.currentPage == pageTotal && (this.totals - 1) % this.pageSize == 0) {
                this.currentPage = this.currentPage - 1
              }
              this.getsystemLogs();
            } else {
              this.$message.error("系统繁忙，请稍后重试！【500】")
            }
          }).catch(res => {
            this.$message.error("系统繁忙，请稍后重试！【400,404,405】")
          })
          this.listLoading = false;
        }).catch(() => { // 取消

        });
      },
      // 选中改变时
      selsChange: function (sels) {
        this.sels = sels.map(obj => obj.id);
      },
      //批量删除
      batchRemove: function () {
        var ids = this.sels
        this.$confirm('确认删除选中记录吗？', '提示', {
          type: 'warning'
        }).then(() => {
          this.listLoading = true;
          this.$http.patch("/systemLog", ids).then(res => {
            this.listLoading = false;
            if (res.data.success) {
              //计算总页数
              let totalPage = Math.ceil(this.totals / this.pageSize)
              if (this.currentPage > 1 && this.currentPage == totalPage && (this.totals - this.sels.length) % this.pageSize == 0) {
                this.currentPage = this.currentPage - 1;
              }
              this.getsystemLogs();
            } else {
              this.$message.error("系统繁忙，请稍后重试![500]");
            }
          }).catch(res => {
            this.$message.error("系统繁忙，请稍后重试![400]");
          })
        }).catch(() => {
        });
      },
      //显示编辑界面
      handleEdit: function (index, row) {
        this.title = '编辑'
        this.saveForm = Object.assign({}, row);
        this.getAdmins();
        this.getDeptTree();
        this.saveFormVisible = true;
        this.fileList = [];
        if (this.saveForm.logo) {
          this.fileList.push({"url": this.saveForm.logo});
        }
      },
      //显示新增界面
      handleAdd: function () {
        this.title = '添加'
        this.saveForm = { // 重置数据
          id: null,
          name: '',
          tel: '',
          registerTime: '',
          address: '',
          logo: '',
          state: 1,
          adminId: null
        };
        this.getAdmins();
        this.getDeptTree();
        this.saveFormVisible = true;
        this.fileList = [];
      },
      //提交按钮
      saveSubmit: function () {
        this.$refs.saveForm.validate((valid) => {
          if (valid) {
            this.$confirm('确认提交吗？', '提示', {}).then(() => {
              this.saveLoading = true;
              this.$http.put("/systemLog", this.saveForm).then(res => {
                this.saveLoading = false;
                this.saveFormVisible = false;
                if (res.data.success) {
                  this.getsystemLogs()
                } else {
                  this.$message.error("系统繁忙，请稍后重试![500]");
                }
              }).catch(res => {
                this.$message.error("系统繁忙，请稍后重试![400]");
              })
            });
          }
        });
      },
      // 获取所有管理员
      getAdmins() {
        this.$http.get("/employee").then(res => {
          this.admins = res.data;
        })
      },
      // 获取部门树
      getDeptTree() {
        this.$http.get("/department/deptTree").then(res => {
          this.deptTree = res.data;
        })
      },
      handleRemove(file, fileList){ // 删除图片
        var filename = file.url.substring(file.url.lastIndexOf("/"+1)); // 获取文件名
        // 调用删除接口
        this.$http.delete("/minio/" + filename).then(res=>{
          if (res.data.success){
            this.$message.success("删除成功");
            this.fileList=[];
            this.saveForm.logo='';
          } else {
            this.$message.error("删除失败");
          }
        })
      },
      handleSuccess(response, file, fileList){ // 上传成功
        // 将地址 + 文件名上传
        this.saveForm.logo = "http://115.159.88.63:9090/java0206/" + response.resultObj;
        // 维护fileList
        this.fileList = [];
        if (this.saveForm.logo){
          this.fileList.push({"url":this.saveForm.logo});
        }
      },
      exceed(){ // 超过文件个数触发
        this.$message.error("只能上传一个文件")
      }
    },
		mounted() {
			this.getsystemLogs();
		}
	}

</script>

<style scoped>

</style>